package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Auther 赵乾坤
 * @Date 2020-12-30 22:40
 */
@RestController
@RequestMapping("/api/user/passport")
public class LoginApiController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate redisTemplate;
    //提交登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        //1:判断用户名是否为NULL  空
        //2:判断密码是否为NULL 空
        //3:查询DB 校验用户名密码 是否正确
        userInfo = loginService.login(userInfo);
        if(null != userInfo){
            Map result = new HashMap<>();
            //传递 token   UUID 36位  4个小横线
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            result.put("token", uuid);
            //昵称
            result.put("nickName",userInfo.getNickName());
            //保存Redis一份
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + uuid,userInfo.getId().toString(),30, TimeUnit.DAYS);
            return Result.ok(result);
        }else{
            return Result.fail().message("用户名或密码不正确");
        }
    }
}
